<?php
// 本类由系统自动生成
namespace Home\Controller;
use Home\Model\WeixinModel;
class IndexController extends PublicController {
	//定义空操作，避免错误反馈
	public function _empty(){ 
		//空操作
	}
    public function weixin(){   
		$WeChat = new WeixinModel();
		$WeChat->run();
	}
    
    public function deletemenu(){
        $WeChat = new WeixinModel();
        $a=$WeChat->getweixin()->deleteMenu();
        var_dump($a);
    }
   
  
    /**
     * 通过code获取用户信息
     * @param string $code
     * @return Ambigous <number, mixed>
     */
    public function getOpenidByCode($code =''){
        $param ['appid']=C("appid");
        $param ['secret'] =C("appsecret");;
        $param ['code'] = $code;
        $param ['grant_type'] = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $token_data =$this->http($url,$param,"GET");
        $openid=-1;
        if($token_data!==""){
            $jsonObj=  json_decode($token_data,true);
            $openid=$jsonObj['openid'];
            if($openid!==-1&&$openid!==''){
                session('openid', $openid);
            }
        }
        return $openid;
    }
    /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    public function http($url, $params, $method = 'GET', $header = array(), $multi = false){
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return  $data;
    }
    
    public function oauth2(){
        if (!empty($_REQUEST['code'])) {
            $code = $_REQUEST['code'];
            $APPID=C("appid");
            $SECRET=C("appsecret");
            $myopenid=urldecode($_REQUEST['openid']);//$_REQUEST['openid'];//邀请人的openid
            if(empty($myopenid)){
                M("log")->data(
                    array(
                        "info"=>json_encode(array("info"=>"get shangxian openid error!")),
                        "times"=>date("Y-m-d H:i:s",time()),
                        "openid"=>"empty",
                        "event"=>"授权"
                        )
                    )->add();
            }
            $openid=$this->getOpenidByCode($code);
            if($openid){
                $model= M("client");
                $userinfo=$model->where(array("openid"=>$openid))->find();//邀请人用户信息
                if(empty($userinfo)){
                    if(!isset($userinfo["shangxian"]) || empty($userinfo["shangxian"])){
                        $userinfo["shangxian"]=$myopenid;
                        $shangxianyinfo=$model->where(array("openid"=>$myopenid))->find();;
                        $userinfo["shangxianname"]=empty($shangxianyinfo["uname"])?"empty":$shangxianyinfo["uname"];
                        $model->where(array("openid"=>$openid))->save($userinfo);
                        M("log")->data(
                        array(
                            "info"=>json_encode(array("info"=>"get info success!yaoqingren is success","yaoqingren"=>$myopenid)),
                            "times"=>date("Y-m-d H:i:s",time()),
                            "openid"=>$openid,
                            "event"=>"授权"
                            )
                        )->add();
                    }else{
                        M("log")->data(
                        array(
                            "info"=>json_encode(array("info"=>"get info success!yaoqingren is all alerdy","yaoqingren"=>$myopenid)),
                            "times"=>date("Y-m-d H:i:s",time()),
                            "openid"=>$openid,
                            "event"=>"授权"
                            )
                        )->add();
                    }
                   session("openid",$openid);
                   Header("Location:".C("host").U("User/yao",array("openid"=>$openid)));
                }else{
                   header("Content-Type:text/html;charset=utf8");
                   echo "邀请人已经关注我们的微信";
                }
            }else{
                M("log")->data(
                array(
                    "info"=>json_encode(array("info"=>"get openid error")),
                    "times"=>date("Y-m-d H:i:s",time()),
                    "openid"=>$openid,
                    "event"=>"授权"
                    )
                )->add();
            }
        }else{
            M("log")->data(
            array(
                "info"=>json_encode(array("info"=>"get code error")),
                "times"=>date("Y-m-d H:i:s",time()),
                "openid"=>$openid,
                "event"=>"授权"
                )
            )->add();
        }
    }
    
	public  function setmenu(){
      	$menudata = array(  
        'button' => array(  
		    array(  
                'type' => 'click',  
                'name' => '开始赚钱', 
		        'key'=>"zhuanqian",       
            ), 
            array(  
                'name'       => '我的信息',  
                'sub_button' => array(  
                    array(  
                        'type' => 'click',  
                        'name' => '个人中心',  
                        'key'=>"ucenter",
                    ),  
                    array(  
                        'type' => 'click',  
                        'name' => '邀请好友',  
                        'key'=>"yaoqing"  
                    ), 
					array(  
                        'type' => 'view',  
                        'name' => '排行榜',  
                        'url'  =>C("host"). U('User/pai'),  
                    ),
					array(  
                        'type' => 'click',  
                        'name' => '收入查询', 
					    'key'=>"chaxun" 
                    ),					
                )  
            ),  
            array(  
                'name'       => '更多',  
                'sub_button' => array(  
                    array(  
                        'type' => 'view',  
                        'name' => '关于我们',  
                        'url'  => C("host"). U('Our/abo'),  
                    ),  
                    array(  
                        'type' => 'view',  
                        'name' => '联系我们',  
                        'url'  =>C("host").U('Our/lian'),    
                    ),  
                    array(  
                        'type' => 'click',  
                        'name' => '联系客服',  
                        'key'  => 'kefu',  
                    ),  
                    
                )  
            ),    
           )  
        );  
      	print_r($menudata);
        $menujson = json_encode($menudata, JSON_UNESCAPED_UNICODE); 
        $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        $getTokenUrl = sprintf($getTokenUrl, C("appid"), C("appsecret"));
        print_r($getTokenUrl);
        $result = json_decode(file_get_contents($getTokenUrl), true);
        $token =C("token");
        if (isset($result['access_token'])) {
            $token = $result['access_token'];
        }
        if (!$token) {
            throw new \Exception('token can not empty');
        }
        
        $createMenuUrl = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $token;
        $opts = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => "Content-type: application/x-www-form-urlencodedContent-Length: " . strlen($menujson) . "" . "Connection: keep-alive" . "Keep-Alive: " . 300 . "",
                'content' => $menujson,
                'timeout' => 120,
            ),
        );
        
        $context = stream_context_create($opts);
        $response = json_decode(file_get_contents($createMenuUrl, false, $context),true);
        print_r($response);
	}
}
